﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;


namespace KB
{
    /// <summary>
    /// E.g.var code = new VerifyCode();
    /// code.CreateVerifyCode();
    /// Session[KEY.Sessions.VerifyCode] = code.OutCode;
    /// </summary>
    public class VerifyCodeUtility
    {
        #region The Constructors

        public VerifyCodeUtility()
        {

        }
        public VerifyCodeUtility(int iCodeLength, bool isTwist)
        {
            Length = iCodeLength;
            IsTwist = isTwist;
        }

        #endregion

        #region The Settings

        private string _outcode = string.Empty;
        private int _length = 4;
        private bool _istwist = true;
        private int _fontSize = 14;
        private int _padding = 1;
        private bool _ischaos = true;
        private Color _chaoscolor = Color.LightGray;
        private Color _backgroundColor = Color.White;
        private Color[] _codecolors = {
                                     Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown,
                                     Color.DarkCyan, Color.Purple
                                 };
        private string[] _fonts = { "Arial", "Georgia" };
        private string _codeserial =
    "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";

        private double _waverate = 3;
        private double _wavephase = 4;

        public int Length
        {
            get { return _length; }
            set { _length = value; }
        }
        public int FontSize
        {
            get { return _fontSize; }
            set { _fontSize = value; }
        }
        public int Padding
        {
            get { return _padding; }
            set { _padding = value; }
        }
        /// <summary>
        /// with noise point
        /// </summary>
        public bool IsChaos
        {
            get { return _ischaos; }
            set { _ischaos = value; }
        }
        /// <summary>
        /// the noise point color
        /// </summary>
        public Color ChaosColor
        {
            get { return _chaoscolor; }
            set { _chaoscolor = value; }
        }
        public Color BackgroundColor
        {
            get { return _backgroundColor; }
            set { _backgroundColor = value; }
        }

        public Color[] CodeColors
        {
            get { return _codecolors; }
            set { _codecolors = value; }
        }

        public string[] Fonts
        {
            get { return _fonts; }
            set { _fonts = value; }
        }

        public string CodeSerial
        {
            get { return _codeserial; }
            set { _codeserial = value; }
        }

        /// <summary>
        /// with twist code
        /// </summary>
        public bool IsTwist
        {
            get { return _istwist; }
            set { _istwist = value; }
        }

        /// <summary>
        /// the wave rate, the bigger the waver,default is 3
        /// </summary>
        public double WaveRate
        {
            get { return _waverate; }
            set { _waverate = value; }
        }

        /// <summary>
        /// the start wave pahase, default is 4,and the value range[0-2*PI)
        /// </summary>
        public double WavePhase
        {
            get { return _wavephase; }
            set { _wavephase = value; }
        }

        /// <summary>
        /// the generated verifycode
        /// </summary>
        public string OutCode
        {
            get { return _outcode; }
            set { _outcode = value; }
        }


        #endregion

        #region CreateVerifyCode Entrance Method

        public void CreateVerifyCode()
        {
            var arr = CodeSerial.Split(',');
            var rand = new Random(unchecked((int)DateTime.Now.Ticks));
            for (var i = 0; i < Length; i++)
            {
                var randValue = rand.Next(0, arr.Length - 1);
                OutCode += arr[randValue];
            }
            CreateImageOnPage();
        }

        #endregion

        #region The Pirvate Method

        #region The Sin Wave Effect
        /// <summary>
        /// the sin wave 
        /// </summary>
        /// <param name="srcBmp">the bitmap</param>
        /// <returns></returns>
        private Bitmap TwistImage(Bitmap srcBmp)
        {
            const double PI2 = 6.283185307179586476925286766559;
            var destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
            var graph = Graphics.FromImage(destBmp);
            graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);
            graph.Dispose();

            var dBaseAxisLen = IsTwist ? destBmp.Height : destBmp.Width;

            for (var i = 0; i < destBmp.Width; i++)
            {
                for (var j = 0; j < destBmp.Height; j++)
                {
                    var dx = IsTwist ? (PI2 * j) / dBaseAxisLen : (PI2 * i) / dBaseAxisLen;
                    dx += WavePhase;
                    var dy = Math.Sin(dx);
                    var nOldX = IsTwist ? i + (int)(dy * WaveRate) : i;
                    var nOldY = IsTwist ? j : j + (int)(dy * WaveRate);

                    var color = srcBmp.GetPixel(i, j);
                    if (nOldX >= 0 && nOldX < destBmp.Width
                        && nOldY >= 0 && nOldY < destBmp.Height)
                    {
                        destBmp.SetPixel(nOldX, nOldY, color);
                    }
                }
            }

            return destBmp;
        }

        #endregion

        #region CreateImage From the Generating Code

        private Bitmap CreateImageCode()
        {
            var fSize = FontSize;
            var fWidth = fSize + Padding;

            var imageWidth = (OutCode.Length * fWidth) + 4 + Padding * 2;
            var imageHeight = fSize * 2 + Padding;

            var image = new Bitmap(imageWidth, imageHeight);

            var g = Graphics.FromImage(image);

            g.Clear(BackgroundColor);

            var rand = new Random();

            //with  noise background
            if (IsChaos)
            {
                var pen = new Pen(ChaosColor, 0);
                var c = Length * 10;

                for (var i = 0; i < c; i++)
                {
                    var x = rand.Next(image.Width);
                    var y = rand.Next(image.Height);

                    g.DrawRectangle(pen, x, y, 1, 1);
                }
            }

            var n1 = (imageHeight - FontSize - Padding * 2);
            var n2 = n1 / 4;
            var top1 = n2;
            var top2 = n2 * 2;

            for (var i = 0; i < OutCode.Length; i++)
            {
                var cindex = rand.Next(CodeColors.Length - 1);
                var findex = rand.Next(Fonts.Length - 1);

                var f = new Font(Fonts[findex], fSize, FontStyle.Bold);
                var b = new SolidBrush(CodeColors[cindex]);

                var top = i % 2 == 1 ? top2 : top1;

                var left = i * fWidth;

                g.DrawString(OutCode.Substring(i, 1), f, b, left, top);
            }
            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            g.Dispose();
            image = TwistImage(image);
            return image;
        }

        #endregion

        #region Show VerifyCodeImage On the Current Page

        private void CreateImageOnPage()
        {
            var ms = new MemoryStream();
            var image = CreateImageCode();

            image.Save(ms, ImageFormat.Png);

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/png";
            HttpContext.Current.Response.BinaryWrite(ms.GetBuffer());

            ms.Close();
            image.Dispose();
        }

        #endregion

        #endregion
    }
}
